var json;
var lastPrice=0;
var curPrice;
var urlprefix = 'http://www.btc38.com/trade/getTradeList30.php?coinname=';
var buyPrice = 0.01900;
var hasAlert=false;
var firstBuy,firstSell;
var standardPrice = 0;

setInterval("testPrice()",15000);

function testPrice(){
    if(!window.localStorage.working){
        return;
    }
    var coinType = 'CNY';
    var coinName = window.localStorage.coinName.toUpperCase();
    if(coinName === 'SYS'){
        coinType = 'BTC';
    }
    var url = urlprefix+ coinName+'&mk_type='+coinType+'&n='+Math.random();
	$.getJSON(url,function(data){
		json = data;
        curPrice = data.tradeStr[0][1];
        firstBuy = data.buyStr[0][0].toFixed(6);
        firstSell = data.sellStr[0][0].toFixed(6);

        var rate = standardPrice / curPrice;
        if(0.97>rate || rate>1.03){
            standardPrice = curPrice;
        }else{
            return;
        }

        buildBody();
		if(curPrice>=window.localStorage.expectedSellPrice || curPrice<=window.localStorage.expectedBuyPrice || hasAlert){
			notification();
		}
	});
}

function buildBody() {
    hasAlert = false;
    var body = window.localStorage.coinName+"当前价："+curPrice+"\r\n买一价:"+firstSell+"  卖一价："+firstBuy +"\r\n";
    var rate = (curPrice/lastPrice - 1).toFixed(2);
    if (rate > 0.03) {
        body += "涨幅"+ rate*100+"%";
        hasAlert = true;
    }
    if (rate < -0.03) {
        body += "跌幅" + rate*(-1)*100+"%";
        hasAlert = true;
    }
    if (0.97 < curPrice/buyPrice < 1.03 ){
        hasAlert = false;
    }
    return body;
}

function notification(){
    var opt = {
        body:buildBody(),
        icon:"BTC_logo.png"
    };
    var noti = new Notification("Chance",opt);
    function closeNoti() {
        noti.close();
    }
    lastPrice = curPrice;
    setTimeout(closeNoti,10000);
}